package com.education.user.controller;

import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.Token;
import com.education.user.pojo.*;
import com.education.user.service.SRoleMenuServiceImpl;
import com.education.user.service.SysMenuService;
import com.education.user.service.SysUserRoleServiceImpl;
import com.education.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: ly
 * @create: 2018-07-05 15:57
 **/
@Api(description = "验证码", tags = {"验证码"})
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SysUserRoleServiceImpl userRoleService;
    @Autowired
    private SRoleMenuServiceImpl roleMenuService;
    @Autowired
    private SysMenuService menuService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/businessDiary/extisUser")
    public boolean extisUser( @RequestParam("sysPhone")String sysPhone){
        return userService.extisUser(sysPhone);
    };


    @PostMapping("/businessDiary/satisfyLogin")
    public boolean satisfyLogin(@RequestBody() User user){
        return userService.satisfyLogin(user);
    };
    /**
     * 校验数据是否可用
     *
     * @param type
     * @param data
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkData(
            @PathVariable(value = "type", required = false) Integer type,
            @PathVariable("data") String data) {
        Boolean boo = this.userService.checkData(data, type);
        if (boo == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return ResponseEntity.ok(boo);
    }

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone) {
        if (StringUtils.isBlank(phone)) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        // TODO 对手机格式进行正则校验

        // 发短信
        this.userService.sendCode(phone);

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, @RequestParam("code") String code) {

        // 保存用户信息
        boolean boo = this.userService.register(user, code);
        if (!boo) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    /**
     * 查询用户信息
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping("query")
    public ResponseEntity<User> queryUserByUsernameAndPassword(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ) {
        User user = this.userService.queryUserByUsernameAndPassword(username, password);
        if (user == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(user);
    }

    /**
     * APP端
     * @param username
     * @param password
     * @return
     */
    @GetMapping("query1")
    public ResponseEntity<User> queryUserByUsernameAndPassword1(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ) {
        User appUser = this.userService.queryUserByUsernameAndPassword1(username, password);
        if (appUser == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(appUser);
    }

    /**
     * APP端
     * @param username
     * @param password
     * @return
     */
    @GetMapping("query2")
    public ResponseEntity<User> queryUserByUsernameAndPassword2(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ) {
        User appUser = this.userService.queryUserByUsernameAndPassword2(username, password);
        if (appUser == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(appUser);
    }

    /**
     * 查询用户对应的菜单列表
     *
     * @param  id
     * @return
     */
    @GetMapping("queryList")
    public ApiReturnObject queryMenuListByUserId(@RequestParam("id") Integer id) {
        //根据userId 查询出对应的角色
        List<SysUserRole> sysUserRoles = userRoleService.selectSysByUserId(id);
        List<SysMenu> children = new ArrayList<>();
        //然后根据角色id 查询出菜单列表
        if(sysUserRoles.size() == 1){
            SysUserRole sysUserRole = sysUserRoles.get(0);
            //根据角色id 查询出菜单id 集合
            List<Integer> menuIds = roleMenuService.selectMenuIdsByRoleId(sysUserRole.getRoleId());
            //根据菜单id 集合查询出菜单集合 第一
            if(sysUserRole.getRoleId() == 1){
                //不分级 查出所有
                List<SysMenu> sysMenus = menuService.selectMenuListTwo(menuIds);
                return new ApiReturnObject("200","查询成功",sysMenus);
            }
            List<SysMenu> sysMenus = menuService.selectMenuList(menuIds);
            // 遍历拼接 出菜单列表一级下级列表
            children = list(sysMenus,sysUserRole.getRoleId());
        }
       /* if (list == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }*/
        return new ApiReturnObject("200","查询成功",children);
    }

    //根据一级菜单查询出子菜单
    //递归集合    根据第一级的id查询出下级列表
    public List<SysMenu> list(List<SysMenu> menus,Integer roleId){
        for (SysMenu menu : menus) {
            //根据第一级的id查询出下级列表
            List<SysMenu> sDeptS = menuService.selectSysMenuByPId(menu.getId(),roleId);
            if(sDeptS != null && sDeptS.size() > 0){
                //设置子级集合
                menu.setChildren(list(sDeptS,roleId));
            }
        }
        return menus;
    }

    @PostMapping("/sendCode")
    @ApiOperation(value = "发送验证码--注册使用", httpMethod = "POST")
    public ApiReturnObject sendCode(SysUser user) throws Exception {
        //根据手机号查询该用户是否存在
        if (user.getSysPhone() != null) {
            //发送验证码
            String verifyCode3 = (int) ((Math.random() * 9 + 1) * 100000) + "";
            redisTemplate.opsForHash().put(user.getSysPhone(), "code", verifyCode3);
            redisTemplate.boundValueOps(user.getSysPhone()).expire(600000, TimeUnit.SECONDS);
            SendSmsUtil.sendSmsTwo(user.getSysPhone(), verifyCode3);
            return new ApiReturnObject("200", "验证码发送成功", "");
        } else {
            return new ApiReturnObject("201", "手机号为空 请输入手机号", "");
        }
    }

    /**
     * 忘记密码
     *
     * @param user
     * @return
     * @throws Exception
     */
    @PostMapping("/passWord")
    public ApiReturnObject forGetPassWord(UserVO user) throws Exception {
        //查询验证码
        String smsCode = (String) redisTemplate.opsForHash().get(user.getSysPhone(), "code");
        if (smsCode != null) {
            if (user.getCode() != null && !"".equals(user.getCode())) {
                String code = user.getCode().toString();
                if (smsCode.equals(code)) {
                    String string = Token.getMD5String(user.getSysPassword());
                    user.setSysPassword(string);
                    userService.updateByPhone(user);
                    return new ApiReturnObject("200", "", "已修改为新密码");
                } else {
                    return new ApiReturnObject("204", "验证码有误", "");
                }
            } else {
                return new ApiReturnObject("202", "请输入验证码", "");
            }
        } else {
            return new ApiReturnObject("201", "请输入验证码", "");
        }
    }

    /**
     *  查询原密码
     */
    @GetMapping("/selectPassword")
    public ApiReturnObject selectPassword(Integer userId){
        if(userId != null){
            User user1 = userService.selectSysUserById(userId);
            if(user1 != null){
                String sysPassword = user1.getSysPassword();
                return new ApiReturnObject("200","查询成功",sysPassword);
            }
            return new ApiReturnObject("201","请检查用户信息","");
        }
        return new ApiReturnObject("201","缺少userId","");
    }


    /**
     * 修改密码
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping("/passWordUpdate")
    public ApiReturnObject forGetPassWordUpdate(Integer userId,String sysPassword,String newSysPassword)  {
        //接受原密码 和 新密码
        if(userId != null){
            User user1 = userService.selectSysUserById(userId);
            if(user1 != null){
                //数据库密码 和 传过来的原密码进行比较
                String md5String = Token.getMD5String(sysPassword);
                //密码匹配 设置新密码
                if(md5String.equals(user1.getSysPassword())){
                    if(!sysPassword.equals(newSysPassword)){
                        //要更改的密码和原密码一致
                        user1.setSysPassword(Token.getMD5String(newSysPassword));
                        userService.updateSysPassword(user1);
                        return new ApiReturnObject("200","修改成功",user1);
                    }
                    return new ApiReturnObject("201","新旧密码一致,请重新设置","");
                }
                return new ApiReturnObject("201", "原密码不正确", "");
            }
            return new ApiReturnObject("201","请检查用户信息","");
        }
        return new ApiReturnObject("201","缺少参数","");
    }

    /**
     * 重置密码
     */
    @GetMapping("/resetPassword")
    private ApiReturnObject resetPassword(Integer id) {
        if (id != null) {
            User user = userService.selectSysUserById(id);
            if (user != null) {
                user.setSysPassword(Token.getMD5String("123456"));
                userService.updateSysPassword(user);
            }
            return new ApiReturnObject("200", "密码已重置为123456", "");
        }
        return new ApiReturnObject("201", "缺少相关参数", "");
    }

    /**
     * 根据id查询用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/queryByUser")
    public Map<String, Object> user(Integer userId) {
        if (userId != null) {
            User user = userService.selectSysUserById(userId);
            Map<String, Object> map = new HashMap<>();
            map.put("sysType", user.getSysType());
            map.put("name", user.getSysRelname());
            map.put("img", user.getSysIco());
            return map;
        }
        return new HashMap<>();
    }

    /*public static void main(String[] args) {
        String md5String = Token.getMD5String("123456");
        System.out.println(md5String);

    }*/
}
